package two;

import javax.sound.midi.*;

public class HappyBirthday {
    public static void main(String[] args) {
        try {
            Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();

            Sequence sequence = new Sequence(Sequence.PPQ, 4);
            Track track = sequence.createTrack();

            ShortMessage first = new ShortMessage();
            first.setMessage(ShortMessage.PROGRAM_CHANGE, 0, 1, 0);
            MidiEvent firstEvent = new MidiEvent(first, 0);
            track.add(firstEvent);

            int[] notes = {60, 60, 62, 60, 65, 64, 60, 60, 62, 60, 67, 65, 60, 60, 72, 69, 65, 64, 62, 70, 70, 69, 65, 67, 65};
            int[] durations = {4, 4, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4};

            for (int i = 0; i < notes.length; i++) {
                ShortMessage a = new ShortMessage();
                a.setMessage(ShortMessage.NOTE_ON, 5, notes[i], 100);
                MidiEvent noteOn = new MidiEvent(a, i * 4);
                track.add(noteOn);

                ShortMessage b = new ShortMessage();
                b.setMessage(ShortMessage.NOTE_OFF, 0, notes[i], 100);
                MidiEvent noteOff = new MidiEvent(b, (i * 4) + durations[i]);
                track.add(noteOff);
            }

            sequencer.setSequence(sequence);
            sequencer.setTempoInBPM(120);

            // 设置循环播放
            sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);

            sequencer.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("HAPPY BIRTHDAY!!!");
    }
}